<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <div class="cd-text-xxlg text-center cd-mb8">
            <span>{{ projectInfo.projectName }}{{ treeInfo.label }}开票明细汇总表</span>
            <el-button v-if="dataList.length > 0" class="top-right-btn" type="warning" plain icon="el-icon-download"
              size="mini" @click="handleExport">
              导出
            </el-button>

          </div>
          <el-table v-show="treeInfo.type == 'bd'" :span-method="objectSpanMethod" :summary-method="getSummaries"
            show-summary border stripe :data="dataList" :max-height="tableHeight"
            :header-row-class-name="titleList.length > 0 ? 'report-table' : ''">
            <el-table-column label="序号" align="center" property="vuhao" />
            <el-table-column prop="sheetTypeName" header-align="center" label="类别" min-width="140"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetTypeName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" header-align="center" min-width="120" property="sheetFeaturesName"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetFeaturesName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sheetUnit" align="center" label="单位" min-width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetUnit || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initRongliang" header-align="center" align="right" label="数量" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initRongliang || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initDanjia" header-align="center" align="right" label="单价" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initDanjia || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initZongjia" header-align="center" align="right" label="总价" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initZongjia || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initZongjiaSum" header-align="center" align="right" label="税价合计" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initZongjiaSum || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sheetTaxRate" header-align="center" align="right" label="税率(%)" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetTaxRate || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="(item, index) in titleList" :key="index" align="center"
              :label="`第${periodsManage(item.kp)}次开发票`">
              <el-table-column header-align="center" align="right" :prop="item.sl" label="数量" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.sl] || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="right" :prop="item.kpje" label="开票金额" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.kpje] || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="right" :prop="item.bqzfje" label="本次付款金额" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.bqzfje] || "-" }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="ljkfje" align="center" label="累计付款金额" min-width="120" show-overflow-tooltip />
            <!-- <el-table-column prop="settleName" align="center" label="备注" min-width="120" show-overflow-tooltip /> -->
          </el-table>
          <el-table v-show="treeInfo.type == 'zd'" :span-method="objectSpanMethod" :summary-method="getSummaries"
            show-summary border stripe :data="dataList" :max-height="tableHeight"
            :header-row-class-name="titleList.length > 0 ? 'report-table' : ''">
            <el-table-column label="序号" align="center" property="vuhao" width="50" />
            <el-table-column prop="sheetTypeName" header-align="center" label="类别" min-width="140"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetTypeName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="规格型号" header-align="center" min-width="120" property="sheetFeaturesName"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetFeaturesName || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sheetUnit" align="center" label="单位" min-width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetUnit || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initRongliang" header-align="center" align="right" label="数量" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initRongliang || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initDanjia" header-align="center" align="right" label="单价" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initDanjia || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initZongjia" header-align="center" align="right" label="总价" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initZongjia || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="initZongjiaSum" header-align="center" align="right" label="税价合计" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.initZongjiaSum || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sheetTaxRate" header-align="center" align="right" label="税率(%)" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.sheetTaxRate || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="(item, index) in titleList" :key="index" align="center"
              :label="`第${periodsManage(item.kp)}次开发票`">
              <!--              :label="`第${periodsManage(item.kp)}次开发票（${item.bl || 0}%）`">-->
              <el-table-column header-align="center" align="right" :prop="item.sl" label="数量" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.sl] || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="right" :prop="item.kpje" label="开票金额" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.kpje] || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="right" :prop="item.bqzfje" label="本次付款金额" min-width="120"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row[item.bqzfje] || "-" }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="ljkfje" header-align="center" align="right" label="累计付款金额" min-width="120"
              show-overflow-tooltip />
            <el-table-column prop="ratio" align="center" label="备注" min-width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ (scope.row.ratio && scope.row.ratio !== '0') ? scope.row.ratio + '%' : "" }}</span>
              </template>
            </el-table-column>
          </el-table>
          <!-- <img v-if="treeInfo.type == 'bd'" src="./2.png" alt="开票明细-标段" style="width: 100%" />
        <img v-if="treeInfo.type == 'zd'" src="./3.png" alt="开票明细-站点" style="width: 100%" /> -->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { queryBdTree } from "@/api/base/bsBd";
import { mapGetters } from "vuex";
import { listBillingInfo } from "@/api/cm/billingDetail";
import decimal from "@/utils/big-decimal";

export default {
  name: "BillingDetail",
  data () {
    return {
      isHide: false,
      projectInfo: {
        projectName: ""
      },
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      titleList: [],
      // table数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        bdId: undefined,
        zdId: undefined
      },
      projectId: undefined,
      dayTableTotal: {},
      fpList: [],
      //合并表格
      columnArr: ["vuhao"],
      spanData: [],
      tableHeight: document.documentElement.scrollHeight - 170 - 30
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectInfo = this.sysProjectList.find((item) => item.projectId === this.projectId);
      this.getBdList();
    },
    getBdList () {
      queryBdTree({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            this.$refs.tree.setCurrentKey(this.treeList[0].id);
            this.handleNodeClick(this.treeList[0]);
          } else {
            this.getList();
          }
        });
      });
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.parentId) {
        this.queryParams.bdId = data.parentId; //标段ID
        this.queryParams.zdId = data.id; //站点ID
      } else {
        this.queryParams.bdId = data.id; //标段ID
        this.queryParams.zdId = undefined; //站点ID
      }
      this.$forceUpdate();
      this.getList();
    },
    getList () {
      this.loading = true;
      listBillingInfo(this.queryParams).then((res) => {
        const { result, resultHeader, total } = res.data;
        this.dataList = result || [];
        this.titleList = resultHeader || [];
        if (this.dataList.length > 0) {
          this.getSpanData(this.dataList);
        }
        this.dayTableTotal = res.data.total || {}; //总计
        this.loading = false;
      });
    },

    // 计算需要合并的单元格
    getSpanData (data) {
      const columns1 = ["vuhao", "sheetTypeName", "initZongjiaSum", "ljkfje"]; // 需要合并的列名
      let columns2 = [];
      if (this.titleList.length > 0) {
        this.titleList.forEach(item => {
          columns2.push(item.bqzfje);
        });
      }
      this.columnArr = [...columns1, ...columns2];
      if (!data || data.length === 0 || !this.columnArr || this.columnArr.length === 0) {
        return;
      }
      this.spanData = [];
      for (let i = 0; i < this.columnArr.length; i++) {
        let contactDot = 0;
        const spanArr = [];
        data.forEach((item, index) => {
          // console.log(item)
          if (index === 0) {
            spanArr.push(1);
          } else {
            const isMergeRow = this.isMerge(data[index - 1], item, i);
            if (isMergeRow) {
              spanArr[contactDot] += 1;
              spanArr.push(0);
            } else {
              contactDot = index;
              spanArr.push(1);
            }
          }
        });
        this.spanData.push(spanArr);
      }

      // console.log(this.spanData);
    },
    // 是否合并
    isMerge (prevItem, item, index) {
      let ret = true;
      // for (let i = 0; i <= index; i++) {
      const element = this.columnArr[index];
      if (item[element] != prevItem[element]) {
        ret = false;
        // break;
      }
      // }
      return ret;
    },
    // 合并单元格
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (this.columnArr.includes(column.property)) {
        const index = this.columnArr.findIndex((item) => {
          return item == column.property;
        });
        if (this.spanData[index]) {
          if (this.spanData[index][rowIndex]) {
            return {
              rowspan: this.spanData[index][rowIndex],
              colspan: 1,
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      }
    },
    // 拼接合计
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        if (column.property == 'initRongliang') {
          sums[index] = this.dayTableTotal?.rongliangTotal || "-";
        } else if (column.property == 'initZongjiaSum') {
          sums[index] = this.dayTableTotal?.zongjiaTotal || "-";
        } else if (column.property == 'ljkfje') {
          sums[index] = this.dayTableTotal?.ljkfje || "-";
        }
        let arr = [];
        if (this.titleList.length > 0) {
          this.titleList.forEach(item => {
            arr.push(item.bqzfje);
            arr.push(item.kpje);
          });
        }
        if (arr.length > 0) {
          arr.forEach(title => {
            if (column.property == title) {
              sums[index] = this.dayTableTotal[title] || "-";
            }
          });
        }
      });
      return sums;
    },

    // 汉字转换
    periodsManage (index) {
      const arr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',];
      return arr[index];
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "cm/baContractSheets/listBillingInfoExport",
        {
          ...this.queryParams
        },
        `开票明细_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .report-table {
  th {
    height: 22px !important;
    padding: 0 !important;
  }
}
</style>
